<template>
  <t-modal
    :title="title"
    :width="900"
    :visible="visible"
    :confirmLoading="loading"
    @cancel="
      () => {
        clear();
        $emit('update:visible', false);
      }
    "
    @ok="ok"
  >
    <a-spin :spinning="spinning">
      <a-card :bordered="true">
        <a-button
          type="link"
          icon="plus-circle"
          style="padding: 0;"
          @click="$refs.checkReportRef.showModal()"
        >
          {{ $ct("AddReport", "新增报表模板") }}
        </a-button>
        <a-table
          :scroll="{ y: 300 }"
          :columns="columns"
          :data-source="dataSource"
          :pagination="false"
          size="middle"
          rowKey="id"
        >
          <span slot="action" slot-scope="text, record, index">
            <a-button
              type="link"
              @click="deleteHandle(record, index)"
              style="color: red;"
            >
              {{ $ct("Delete", "删除") }}
            </a-button>
          </span>
        </a-table>
      </a-card>
    </a-spin>
    <checkReport ref="checkReportRef" @confirm="reportConfirm" />
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
// 表单字段
const fields = ["name", "uuid", "id"];
import pick from "lodash.pick";
import checkReport from "./checkReport.vue";
export default {
  props: {
    visible: {
      type: Boolean,
      default: () => false,
    },
    loading: {
      type: Boolean,
      default: () => false,
    },
    model: {
      type: Object,
      default: () => null,
    },
  },
  components: {
    checkReport,
  },
  data() {
    return {
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 4,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 20,
        },
      },
      title: this.$ct("bindReport", "绑定报表"),
      columns: [
        {
          title: "报表名称",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: 100,
        },
      ],
      dataSource: [],
      dataSourceNoVail: [],
      fields,
      form: this.$form.createForm(this),
      leftAlignId: 1, //高亮
      leftAlignIndex: 0,
      spinning: false, //加载
      jsonData: null,
    };
  },
  mounted: function() {},
  created() {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v));
    // 当 model 发生改变时，为表单设置值
    this.$watch("model", () => {
      this.$nextTick(() => {
        this.model && this.form.setFieldsValue(pick(this.model, fields));
      });
    });
  },
  methods: {
    add(m) {
      if (m) {
        this.spinning = true;
        this.$post("/form/formBasicConfigure/getDetailByUuid", {
          uuid: m.uuid,
        })
          .then((res) => {
            if (res?.formList) {
              this.jsonData = res;
              let reportList = JSON.parse(res.formList.webListJson);
              let printJson = reportList.listProData.lineButtonList.find(
                (item) => item.btnType == "print"
              );
              printJson.list.map((item) => {
                this.addTopButton(item);
              });
            } else {
              this.$message.wran(res.message);
            }
            this.spinning = false;
          })
          .catch((err) => (this.spinning = false));
      } else {
      }
      this.$emit("update:visible", true);
    },
    ok() {
      this.saveJson();
    },
    saveJson() {
      let webListJson = this.jsonData.formList.webListJson;
      let appListJson = this.jsonData.formList.appListJson;
      let btnJson = {
        allowDelete: true,
        btnStyle: "cu-btn-primary",
        btnType: "print",
        checked: true,
        disabled: false,
        icon: "",
        interface: "",
        label: "打印报表",
        name: "打印报表",
        permissionId: null,
      };
      btnJson.list = this.dataSource.map((item) => item.name);
      let parseData = JSON.parse(webListJson);
      let index = parseData.listProData.lineButtonList.findIndex(
        (item) => item.btnType == "print"
      );
      if (index >= 0) {
        //添加打印的方式
        parseData.listProData.lineButtonList[index] = btnJson;
      } else {
        parseData.listProData.lineButtonList.push(btnJson);
      }
      if (btnJson.list.length == 0) {
        //为空删除打印
        index = parseData.listProData.lineButtonList.findIndex(
          (item) => item.btnType == "print"
        );
        parseData.listProData.lineButtonList.splice(index, 1);
      }
      this.jsonData.formList.webListJson = JSON.stringify(parseData);
      let param = {
        basicConfigureJson: JSON.stringify(
          this.getValFromJson(
            [
              "code",
              "uuid",
              "moduleUuid",
              "name",
              "status",
              "sort",
              "configureDesc",
              "type",
            ],
            this.jsonData.formBasicConfigure
          )
        ),
        databaseJson: this.jsonData.formDatabase.databaseJson,
        fromJson: this.jsonData.formDesign.designJson,
        appDesignJson: this.jsonData.formDesign.appDesignJson,
        webListJson: this.jsonData.formList.webListJson,
        appListJson: this.jsonData.formList.appListJson,
        newVersion: false,
      };
      this.handleSubmitSave(param);
    },
    getValFromJson(val, json) {
      let item = {};
      val.map((items) => {
        item[items] = json[items];
      });
      return item;
    },
    handleSubmitSave(param) {
      this.spinning = true;
      axios
        .post("/form/formBasicConfigure/save", param, {
          headers: {
            "Content-Type": "application/json;charset=UTF-8",
          },
        })
        .then((res) => {
          if (res.statusCode !== 300) {
            this.$message.success(
              res.message ? res.message : "操作成功！",
              1.5
            );
            this.$emit("ok", this.dataSourceNoVail);
            this.$emit("update:visible", false);
            this.clear();
          } else {
            this.$message.error(res.message ? res.message : "操作失败", 1.5);
          }
          this.spinning = false;
        });
    },
    deleteHandle(value, index) {
      this.dataSource.splice(index, 1);
    },
    reportConfirm(row) {
      this.$nextTick(() => {
        row.map((item) => {
          this.addTopButton(item.dataReportName);
        });
      });
    },
    addTopButton(item = undefined) {
      if (!item) {
        this.$message.info("报表名称不能为空");
        return;
      }
      let find = this.dataSource.find((items) => items.name == item);
      if (find) {
        return;
      }
      let lastKey = this.dataSource[this.dataSource.length - 1]?.id;
      let index = (lastKey ? lastKey : 0) + 1;
      this.dataSource.push({
        name: item,
        id: index,
      });
    },
    clear() {
      this.dataSource.length = 0;
      this.jsonData = null;
    },
  },
};
</script>

<style scoped lang="scss">
.err-an {
  background-color: red;
}
</style>
